\chapter{Implementation}

\section{Technology Choices}

\input{why-python} \input{why-numpy} \input{why-vpython}

\section{Implementing The Time Chess Engine}

This section covers two levels of detail. One is the broad overview
to give a feel of the structure of the software, and the other is
specific and quite detailed description of the workings of the
program wherever it is doing something particularly complicated or
interesting.

\subsection{Implementation Description}

If the whole system is a form of Model View Controller, then the
engine plays the part of the model and the controller, with the
interface playing the part of the view.

\subsubsection{The \texttt{Pos} Object}

\verb!Pos! objects represent positions in the game. They have three
coordinates, $x$, $y$ and $t$. They can be initialised either by
giving these coordinates separately, or in the form of \TC Position
Notation (see section \ref{move-notation}).

\subsubsection{The \texttt{Piece} Object}

\verb!Piece! is a parent class for the subclasses \verb!Pawn!,
\verb!Rook!, \verb!Knight!, \verb!Bishop!, \verb!Queen! and
\verb!King!. Objects of these classes represent pieces, but more
specifically they represent a specific instance of a piece in a
game. For example, the White King is one piece in the game, but is
represented by several \verb!King! objects, one for each turn in
which the King exists. If the King doesn't move, there might be
\verb!King! objects at \verb!e1t0!, \verb!e1t1!, \verb!e1t2! and so
on. Two \verb!Piece! objects represent the same in-game piece if
they share the same \verb!pieceId! attribute. The \verb!Piece!
objects representing one in-game piece form a `lineage' , with the
same \verb!pieceId! attributes and sequential \verb!age!
attributes.

\subsubsection{The \texttt{Game} Object}
\label{game-implementation} Within the MVC structure, the
\verb!Game! is the model. It is effectively a data structure class,
mostly concerned with storing the state of the board in a game of
\TC. It inherits from a NumPy array object, and can be thought of
as a thin wrapper around a three-dimensional array of \verb!Piece!
objects. A major function of this wrapper is to allow the array to
be indexed into using \verb!Pos! objects, but it also provides some
extra functionality for finding sets of pieces that meet certain
criteria.

\subsubsection{The \texttt{TimeChessEngine} Object}

The \verb!TimeChessEngine! object plays the role of the controller
in the MVC architecture. It contains a \verb!Game! object, and
manipulates it in accordance with the rules of \TC as the game
progresses. It handles commands from the view mostly using the
\verb!attemptMove! method, through which the view can relay
intended moves from the user. The \verb!TimeChessEngine! is
responsible for calculating if moves are legal, and working through
their ramifications on the state of the \verb!Game! object.

\subsection{How it works}

\input{implementation-engine-howitworks}

\section{Implementing the 3D Interface}

\subsection{Implementation Description}

\subsubsection{The \texttt{Piece} Object}

The \verb!Piece! object represents a 3D object that looks like a
Chess piece. It gets most of its functionality by inheriting from
the VPython \verb!frame! object, which is designed as a container
for other VPython 3D objects. The \verb!frame! holds all of the
objects together in one frame of reference, effectively grouping
them into a more complex 3D object. For example, a \verb!Piece!
representing a pawn groups together a \verb!cone! object and a
\verb!sphere! object, which together form the shape of a pawn.

\subsubsection{The \texttt{Ghost} Object}

The \verb!Ghost! object represents `ghost' pieces, which are
semitransparent pieces used to indicate positions where pieces will
come out of time travel in the future. They inherit from
\verb!Piece! and their only difference is a lower opacity.

\subsubsection{The \texttt{Layer} Object}

The \verb!Layer! object represents the state of the board during
one turn of the \TC game. It also inherits from \verb!frame!, and
groups together some \verb!curve! objects, which show as white
gridlines separating the positions on the board, and the
\verb!Piece! objects on the board.

\subsubsection{The \texttt{Controller} Object}

The \verb!Controller! object is responsible for conveying user
input to the game engine, and updating the 3D scene to show the
results.

\subsection{How it Works}

\subsubsection{Overview}

When the program is started, a controller object is created. The
\verb!Controller! object initialises itself and opens a connection
to a program which is started by a command given on the command
line. The intention is for this program to be an engine or other
program that supports TCECP through \verb!stdin! and \verb!stdout!.
In this implementation this is \verb!TCECPInterface.py!, which runs
a \verb!TimeChessEngine! object, supplying it with commands it
receives, and returning the results.

The \verb!Controller! then enters a game loop, in which it handles
mouse and keyboard input from the user. When interaction with the
engine is required, the \verb!send!, \verb!recv! and
\verb!communicate! methods are used to send and receive TCECP
messages.

The \verb!showLayer! and \verb!hideLayer! methods are used to
create and hide layers of the board, and the \verb!makeHighlight!
and \verb!clearHighlights! methods are used to create and destroy
possible move highlights.

\subsubsection{Creating Pieces}

\singlespacing
\begin{figure}[h]
\fbox{
    \begin{minipage}{\textwidth}
    \small{
    \input{makePiece.tex}
    }
    \end{minipage}
}
\caption{System to generate 3D objects from stored geometry information}
\label{fig-makePiece}
\label{fig-makepiece}
\end{figure}
\doublespacing

Because \verb!Piece! objects have no behaviour determined by their
type, it didn't make sense to have a large number of subclasses,
one for each piece type. There is only one \verb!Piece! class,
which can have the appearance of any piece type. This is achieved
by a data structure that stores the attributes of the 3D objects
that make up each piece type, and a generalised method to build
them, which makes use of a lot of Python's more advanced features,
such as tuple unpacking, module dictionaries and keyword argument
unpacking. The \verb!geometries! data structure is a Python
dictionary (like a hash table) which uses piece type characters
(`b' for bishop, `r' for rook etc) as the index to store a list of
entries which form the instructions to make a specific simple
geometric object. This is best demonstrated with examples. In
figure \ref{fig-makepiece}, we can see that the pawn piece type
(represented by the character `p') is made up of two pieces of
geometry; The first is a \verb!cone! positioned at the origin, with
an \verb!axis! of 0.5 units straight up, and a radius of 0.3 units,
and the second is a \verb!sphere! located 0.5 units up from the
origin (at the top of the cone), with a radius of 0.15 units.

The last two lines of figure \ref{fig-makePiece} construct the
required geometry objects for the given piece type (stored in the
\verb!ptype! variable). The \verb!for! loop iterates over the list
returned by \verb!geometries[ptype]!, and unpacks each item into
the variables \verb!prim! and \verb!args!. In the case of a pawn,
where \verb!ptype='p'!, the first iteration of the loop would occur
with \verb!prim="cone"! and \verb!args={"pos":(0,0,0),!
\verb!"axis":(0,0,.5),! \verb!"radius":.3}!. Inside the loop, the
`builtin' dictionary of the \verb!visual! module is accessed by the
\verb!__dict__! attribute. Indexing into the module's
\verb!__dict__! with the key \verb!"cone"! returns the constructor
for the \verb!cone! object, which is then called. The \verb!**!
before the \verb!args! argument informs Python that \verb!args! is
a dictionary which is to be unpacked into keyword arguments. So for
the first iteration of the loop for a pawn, the line

\small \verb!visual.__dict__[prim](frame=self, color=col,**args)!
\normalsize

\noindent is effectively translated into

\small \verb!cone(frame=self,! \verb!color=col,!
\verb!pos=(0,0,0),! \verb!axis=(0,0,.5),! \verb!radius=.3)!
\normalsize

\noindent This sort of dynamic introspection is one of the things
that makes Python such a powerful language.

\subsubsection{Displaying Layers}

The process of using the TCECP interface to request the contents of
a layer from the engine and then constructing 3D objects from that
data is time consuming, and should not be done more often than
necessary. So, \verb!Layer! objects have a \verb!turnMade!
attribute, which stores the turn the game was at when the
\verb!Layer! was made. When the \verb!Controller! requires a layer
to be displayed, it calls the \verb!showLayer! method, which first
checks the existing \verb!Layer! object for that layer to see if it
was made this turn and thus is up to date. If the layer is out of
date, \verb!buildLayer! is called to create a new \verb!Layer!
object with data fetched from the engine.

The \verb!hideLayer! method does not destroy the \verb!Layer!
object, but simply sets its \verb!visible! attribute to
\verb!False!. The \verb!visible! attribute is an attribute of the
VPython \verb!frame! object, which causes the object to disappear
from the 3D scene, but stay in memory. If \verb!showLayer! is
called and an existing \verb!Layer! object is up to date, it is
simple set to be \verb!visible!, and no new layer must be built.
This effectively works as a cache of 3D objects, improving
performance.

\section{Extra Features}

\label{extra-features}

\subsection{Stereo}

In the course of a game of \TC, complex 3D configurations of pieces
must be analysed. This can become difficult when there are many
overlapping layers of varying opacity, because the user has no
sense of depth perception.

\begin{figure}[h]
\begin{center}
\includegraphics[width=1\textwidth]{img/nostereo}
\caption{Complex, densely layered scenes can be difficult to understand}
\label{fig-nostereo}
\end{center}
\end{figure}

By rendering two images of the scene as seen from slightly offset
camera positions, and mapping the right one to the red channel and
the left to the blue channel (figure \ref{fig-redblue}), a
stereoscopic 3D effect can be produced for users wearing red/blue
filter glasses (figure \ref{fig-redblue-glasses})
\cite{konrad20073D}.

Since user preference will vary, and not all users will have
red/blue glasses available to them, this feature can be toggled on
and off with the `\verb!s!' key.

\begin{figure}[h]
\begin{center}
\includegraphics[width=1\textwidth]{img/redblue}
\caption{Red/Blue Stereo can enormously improve game immersion and ease of use}
\label{fig-redblue}
\end{center}
\end{figure}

\begin{figure}[h]
\begin{center}
\includegraphics{img/redblue-glasses}
\caption{Red/Blue Filter Glasses used for stereo viewing}
\label{fig-redblue-glasses}
\end{center}
\end{figure}

